const express = require('express');

const stringFormat = require('../util.js')
 
let router = express.Router();
const bodyParser = require('body-parser')

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended: false}));
 
const mysql = require('mysql');


//实现本地链接
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'test'
})

 
router.get('/list', function (req, res) {
	res.status(200);
	connection.query('SELECT * FROM t_chapter ', function (error, results, fields) {
	        if (error) 
	            throw error;
	        res.json(results);
	        console.log('results is:', results);
	    });
});

router.post('/add', function (req, res) {
    var title = req.body.title;
    var author = req.body.author;
	var tags = req.body.tags;
	var summary = req.body.summary;
	var image = req.body.image;
	var rating = req.body.rating;
	
	let sql = stringFormat("insert into t_chapter(title,author,tags,summary,image,rating) values('{0}','{1}','{2}','{3}','{4}',{5})",title,author,tags,summary,image,rating);
    console.log("add sql", sql);
	connection.query(sql, function (err, rows) {
        if (err) {
            res.end('新增失败：' + err);
        } else {
            res.end('新增成功：' + err);
        }
    })
});

 
router.get('/:id', function (req, res) {
	res.status(200);
	connection.query('SELECT * FROM t_chapter where id = ?', req.params.id, function (error, results, fields) {
	        if (error) 
	            throw error;
	        res.json(results);
	       // console.log('results is:', results);
	    });
});


 
//导出该路由
module.exports = router;